import { config } from '../config.js';
import ResponseFormatter from '../utils/ResponseFormatter.js';

/**
 * 基础中间件类 - 为所有中间件提供统一的接口和通用功能
 */
export class BaseMiddleware {
    constructor(options = {}) {
        this.options = {
            enabled: true,
            priority: 0,
            ...options
        };
        this.name = this.constructor.name;
    }

    /**
     * 中间件执行方法 - 子类必须实现
     * @param {Request} req - Express请求对象
     * @param {Response} res - Express响应对象
     * @param {Function} next - Express next函数
     */
    async execute(req, res, next) {
        throw new Error(`Middleware '${this.name}' must implement execute method`);
    }

    /**
     * 获取中间件函数
     * @returns {Function} Express中间件函数
     */
    getMiddleware() {
        return async (req, res, next) => {
            try {
                // 检查中间件是否启用
                if (!this.options.enabled) {
                    return next();
                }

                // 执行前置钩子
                await this.beforeExecute(req, res);

                // 执行主要逻辑
                await this.execute(req, res, next);

                // 执行后置钩子
                await this.afterExecute(req, res);
            } catch (error) {
                this.handleError(error, req, res, next);
            }
        };
    }

    /**
     * 执行前置钩子
     * @param {Request} req - Express请求对象
     * @param {Response} res - Express响应对象
     */
    async beforeExecute(req, res) {
        // 子类可以重写此方法
        this.logRequest(req, 'BEFORE');
    }

    /**
     * 执行后置钩子
     * @param {Request} req - Express请求对象
     * @param {Response} res - Express响应对象
     */
    async afterExecute(req, res) {
        // 子类可以重写此方法
        this.logRequest(req, 'AFTER');
    }

    /**
     * 错误处理
     * @param {Error} error - 错误对象
     * @param {Request} req - Express请求对象
     * @param {Response} res - Express响应对象
     * @param {Function} next - Express next函数
     */
    handleError(error, req, res, next) {
        console.error(`[${this.name}] Error:`, {
            message: error.message,
            stack: error.stack,
            url: req.originalUrl,
            method: req.method,
            timestamp: new Date().toISOString()
        });

        // 如果响应已经发送，则传递给下一个错误处理器
        if (res.headersSent) {
            return next(error);
        }

        // 根据错误类型返回适当的响应
        if (error.name === 'ValidationError') {
            return ResponseFormatter.validationError(res, error.message);
        }
        
        if (error.name === 'UnauthorizedError') {
            return ResponseFormatter.unauthorized(res, error.message);
        }
        
        if (error.name === 'ForbiddenError') {
            return ResponseFormatter.forbidden(res, error.message);
        }

        // 默认服务器错误
        const message = config.env === 'development' ? error.message : 'Internal Server Error';
        const details = config.env === 'development' ? error.stack : null;
        return ResponseFormatter.error(res, message, 500, details);
    }

    /**
     * 记录请求日志
     * @param {Request} req - Express请求对象
     * @param {string} phase - 执行阶段
     */
    logRequest(req, phase = 'EXECUTE') {
        if (config.log.console && this.options.debug) {
            console.log(`[${this.name}][${phase}] ${req.method} ${req.originalUrl}`, {
                ip: req.ip,
                userAgent: req.get('User-Agent'),
                timestamp: new Date().toISOString()
            });
        }
    }

    /**
     * 验证请求参数
     * @param {Request} req - Express请求对象
     * @param {Object} rules - 验证规则
     * @returns {Object} 验证结果
     */
    validateRequest(req, rules) {
        const errors = [];
        const data = { ...req.body, ...req.query, ...req.params };

        for (const [field, rule] of Object.entries(rules)) {
            const value = data[field];

            // 必填验证
            if (rule.required && (value === undefined || value === null || value === '')) {
                errors.push(`Field '${field}' is required`);
                continue;
            }

            // 如果字段不存在且不是必填，跳过其他验证
            if (value === undefined || value === null) {
                continue;
            }

            // 类型验证
            if (rule.type && typeof value !== rule.type) {
                errors.push(`Field '${field}' must be of type ${rule.type}`);
            }

            // 长度验证
            if (rule.minLength && value.length < rule.minLength) {
                errors.push(`Field '${field}' must be at least ${rule.minLength} characters long`);
            }

            if (rule.maxLength && value.length > rule.maxLength) {
                errors.push(`Field '${field}' must be no more than ${rule.maxLength} characters long`);
            }

            // 正则验证
            if (rule.pattern && !rule.pattern.test(value)) {
                errors.push(`Field '${field}' format is invalid`);
            }

            // 自定义验证
            if (rule.validator && typeof rule.validator === 'function') {
                const customResult = rule.validator(value);
                if (customResult !== true) {
                    errors.push(customResult || `Field '${field}' validation failed`);
                }
            }
        }

        return {
            isValid: errors.length === 0,
            errors,
            data
        };
    }

    /**
     * 获取客户端IP地址
     * @param {Request} req - Express请求对象
     * @returns {string} IP地址
     */
    getClientIP(req) {
        return req.ip || 
               req.connection.remoteAddress || 
               req.socket.remoteAddress || 
               (req.connection.socket ? req.connection.socket.remoteAddress : null) ||
               '0.0.0.0';
    }

    /**
     * 检查请求是否来自可信来源
     * @param {Request} req - Express请求对象
     * @returns {boolean} 是否可信
     */
    isTrustedSource(req) {
        const trustedIPs = this.options.trustedIPs || ['127.0.0.1', '::1'];
        const clientIP = this.getClientIP(req);
        return trustedIPs.includes(clientIP);
    }

    /**
     * 启用中间件
     */
    enable() {
        this.options.enabled = true;
        console.log(`✓ Middleware '${this.name}' enabled`);
    }

    /**
     * 禁用中间件
     */
    disable() {
        this.options.enabled = false;
        console.log(`✓ Middleware '${this.name}' disabled`);
    }

    /**
     * 获取中间件信息
     * @returns {Object} 中间件信息
     */
    getInfo() {
        return {
            name: this.name,
            enabled: this.options.enabled,
            priority: this.options.priority,
            options: this.options
        };
    }
}

export default BaseMiddleware;